package com.pocketsweet.ui;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.C;
import com.pocketsweet.MLContext;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLTask;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.service.shareApp;
import com.pocketsweet.service.shareApp.shareCompleteListener;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_task)
public class Task extends BaseActivity implements OnClickListener {

	@ViewInject(R.id.imgTaskPic)
	private static ImageView imgTaskPic;

	@ViewInject(R.id.mainHeader)
	private static HeaderLayout header;

	@ViewInject(R.id.tvTaskTitle)
	private static TextView tvTaskTitle;

	@ViewInject(R.id.tvInviteStatus)
	private static TextView tvInviteStatus;

	@ViewInject(R.id.inviteStatus)
	private static TextView inviteStatus;

	@ViewInject(R.id.tvInfo)
	private static TextView tvInfo;

	@ViewInject(R.id.tvReward)
	private static TextView tvReward;

	@ViewInject(R.id.tvConsummateTitle)
	private static TextView tvConsummateTitle;

	@ViewInject(R.id.tvConsummateStatus)
	private static TextView tvConsummateStatus;

	@ViewInject(R.id.consummateStatus)
	private static TextView consummateStatus;

	@ViewInject(R.id.tvConsummateInfo)
	private static TextView tvConsummateInfo;

	@ViewInject(R.id.tvConsummateReward)
	private static TextView tvConsummateReward;

	private MLUser mlUser;
	private LoadingDailog mLoadingDialog;
	private shareApp myShareApp;// 分享app

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlUser = UserService.getCurrentUser();
		mLoadingDialog = ToolKits.createLoadingDialog(Task.this, "上传中");
		mLoadingDialog.setText("加载中");
		setHeaderFunction();
		initListener();
		// MLContext.saveTask(MLContext.TASK_INVITE_FRIEND,
		// C.TASK_UNFINISH);//测试，设置任务未完成，之后要删掉
	}

	@Override
	protected void onResume() {
		super.onResume();
		getTask();
	}

	private void getTask() {
		if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_NORECORD
				|| MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_NORECORD) { // 当sharepreference为空时从网络获取
			mLoadingDialog.show();
			AVQuery<MLTask> query = new AVQuery<MLTask>("MLTask");
			query.whereEqualTo("user", mlUser);
			query.findInBackground(new FindCallback<MLTask>() {

				@Override
				public void done(List<MLTask> mlTasks, AVException e) {
					mLoadingDialog.dismiss();
					if (e == null) {
						if (mlTasks.size() > 0) {// 当leanClound上有此用户的任务时，把任务状态保存到本地
							for (int i = 0; i < mlTasks.size(); i++) { // 把用户的任务存到本地
								if (mlTasks.get(i).getType() == C.TASK_INVITE_FRIEND) { // 有邀请好友的任务状态
									MLContext.saveTask(
											MLContext.TASK_INVITE_FRIEND,
											mlTasks.get(i).getStatus());
								} else if (mlTasks.get(i).getType() == C.TASK_CONSUMMATE) {// 有完善资料的任务状态
									MLContext.saveTask(
											MLContext.TASK_CONSUMMATE, mlTasks
													.get(i).getStatus());
								}
							}
							if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_NORECORD) { // 把leanClound没有记录的任务也保存到本地
								MLContext.saveTask(
										MLContext.TASK_INVITE_FRIEND,
										C.TASK_UNFINISH); // 设置为未完成
							}
							if (MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_NORECORD) {// 把leanClound没有记录的任务也保存到本地
								MLContext.saveTask(MLContext.TASK_CONSUMMATE,
										C.TASK_UNFINISH);// 设置为未完成
							}
							changeTask(); // 初始化任务状态
						} else { // 当leanClound没有任务时,把任务状态保存到本地
							MLContext.saveTask(MLContext.TASK_CONSUMMATE,
									C.TASK_UNFINISH);
							MLContext.saveTask(MLContext.TASK_INVITE_FRIEND,
									C.TASK_UNFINISH);
							changeTask();
						}
					} else {
						// Log.e("==getTask==",
						// "getTask ERROR!!!!!!!!!!!" + e.getMessage());
					}
				}
			});
		} else {
			changeTask();
		}
	}

	// 初始化任务状态
	protected void changeTask() {
		// MLContext.saveTask(MLContext.TASK_CONSUMMATE,
		// C.TASK_UNFINISH);//重新测试完善资料，先设置成未完成
		// Log.e("==task=",
		// String.valueOf(MLContext.getTask(MLContext.TASK_INVITE_FRIEND))
		// + " "
		// + String.valueOf(MLContext
		// .getTask(MLContext.TASK_CONSUMMATE)));
		if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_UNFINISH) { // 邀请好友任务
																					// 未完成
			tvInviteStatus.setText(getResources().getString(
					R.string.task_unfinish));
			inviteStatus.setText(getResources().getString(
					R.string.task_go_finish));
			inviteStatus.setTextColor(getResources().getColor(R.color.white));
			inviteStatus.setBackgroundResource(R.drawable.shape_task_unfinish);
		} else if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_GET_REWARD) {// 去领取
			tvInviteStatus.setText(getResources().getString(
					R.string.task_unfinish));
			inviteStatus.setText(getResources().getString(R.string.task_get));
			inviteStatus.setTextColor(getResources().getColor(R.color.white));
			inviteStatus
					.setBackgroundResource(R.drawable.shape_task_get_reward);
		} else if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_FINISH) {// 已完成
			tvInviteStatus.setText(getResources().getString(
					R.string.task_finish));
			inviteStatus.setText(getResources().getString(R.string.task_got));
			inviteStatus
					.setTextColor(getResources().getColor(R.color.text_999));
			inviteStatus.setBackgroundResource(R.drawable.shape_task_finish);

		}
		if (MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_UNFINISH) { // 完善资料任务
																				// 未完成
			tvConsummateStatus.setText(getResources().getString(
					R.string.task_unfinish));
			consummateStatus.setText(getResources().getString(
					R.string.task_go_finish));
			consummateStatus.setTextColor(getResources()
					.getColor(R.color.white));
			consummateStatus
					.setBackgroundResource(R.drawable.shape_task_unfinish);
		} else if (MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_GET_REWARD) {// 去领取
			tvConsummateStatus.setText(getResources().getString(
					R.string.task_get));
			consummateStatus.setText(getResources()
					.getString(R.string.task_get));
			consummateStatus.setTextColor(getResources()
					.getColor(R.color.white));
			consummateStatus
					.setBackgroundResource(R.drawable.shape_task_get_reward);

		} else if (MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_FINISH) {// 已完成
			tvConsummateStatus.setText(getResources().getString(
					R.string.task_finish));
			consummateStatus.setText(getResources()
					.getString(R.string.task_got));
			consummateStatus.setTextColor(getResources().getColor(
					R.color.text_999));
			consummateStatus
					.setBackgroundResource(R.drawable.shape_task_finish);

		}
	}

	private void initListener() {
		inviteStatus.setOnClickListener(this);
		consummateStatus.setOnClickListener(this);
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("");
		header.setMiddleText("奖励");
		header.setLeftContainerClickListener(new onLeftContainerListener() {
			@Override
			public void onClick() {
				Task.this.finish();
			}
		});
	}

	private void setCompleteShare() {// 设置分享的任务完成情况
		if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) != C.TASK_FINISH) { // 如果分享未完成和任务未领取，则可领取任务
			MLContext.saveTask(MLContext.TASK_INVITE_FRIEND, C.TASK_GET_REWARD);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.consummateStatus:
			if (MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_UNFINISH) {// 未完成
				Intent intent = new Intent(Task.this, ProfileEdit.class);
				intent.putExtra("task", true);
				startActivity(intent);
			} else if (MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_GET_REWARD) {// 去领取
				mLoadingDialog.show();
				MLTask mlTask = new MLTask(); // 保存任务到leanClound
				mlTask.setStatus(C.TASK_FINISH);
				mlTask.setType(C.TASK_CONSUMMATE);
				mlTask.setUser(mlUser);
				mlTask.saveInBackground(new SaveCallback() {

					@Override
					public void done(AVException arg0) {
						// TODO Auto-generated method stub
						if (arg0 == null) {
							UserService.getCurrentUser().refreshInBackground(
									new RefreshCallback<AVObject>() {

										@Override
										public void done(AVObject arg0,
												AVException arg1) {
											if (arg1 == null) {
												mlUser = UserService
														.getCurrentUser();
												double balance = mlUser
														.getBalance();
												mlUser.setBalance(balance + 0.5);// 增加5时光
												mlUser.saveInBackground(new SaveCallback() {

													@Override
													public void done(
															AVException arg0) {
														// TODO Auto-generated
														// method stub
														mLoadingDialog
																.dismiss();
														if (arg0 == null) {
															ToolKits.toast(
																	Task.this,
																	"领取成功");
															MLContext
																	.saveTask(
																			MLContext.TASK_CONSUMMATE,
																			C.TASK_FINISH);
															changeTask();
														} else {
															ToolKits.toast(
																	Task.this,
																	"领取失败，请重试");
														}
													}
												});
											} else {
												ToolKits.toast(Task.this,
														"领取失败，请重试");
											}
										}
									});

						} else {
							ToolKits.toast(Task.this, "领取失败，请重试");
						}
					}
				});
			} else if (MLContext.getTask(MLContext.TASK_CONSUMMATE) == C.TASK_FINISH) {// 已完成
			}
			break;
		case R.id.inviteStatus: // TODO 邀请好友任务
			if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_UNFINISH) {// 未完成
				myShareApp = new shareApp(Task.this);
				myShareApp.setCompleteListener(new shareCompleteListener() {
					@Override
					public void onComplate() {
						setCompleteShare();
						ToolKits.toast(Task.this, "分享成功");
						changeTask();// 更改任务ui状态
					}
				});
				myShareApp.startShare();
			} else if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_GET_REWARD) {// 去领取
				mLoadingDialog.show();
				MLTask mlTask = new MLTask(); // 保存任务到leanClound
				mlTask.setStatus(C.TASK_FINISH);
				mlTask.setType(C.TASK_INVITE_FRIEND);
				mlTask.setUser(mlUser);
				mlTask.saveInBackground(new SaveCallback() {

					@Override
					public void done(AVException arg0) {
						// TODO Auto-generated method stub
						if (arg0 == null) {
							UserService.getCurrentUser().refreshInBackground(
									new RefreshCallback<AVObject>() {

										@Override
										public void done(AVObject arg0,
												AVException arg1) {
											if (arg1 == null) {
												mlUser = UserService
														.getCurrentUser();
												double balance = mlUser
														.getBalance();
												mlUser.setBalance(balance + 0.5);// 增加5时光
												mlUser.saveInBackground(new SaveCallback() {

													@Override
													public void done(
															AVException arg0) {
														// TODO Auto-generated
														// method stub
														mLoadingDialog
																.dismiss();
														if (arg0 == null) {
															ToolKits.toast(
																	Task.this,
																	"领取成功");
															MLContext
																	.saveTask(
																			MLContext.TASK_INVITE_FRIEND,
																			C.TASK_FINISH);
															changeTask();
														} else {
															ToolKits.toast(
																	Task.this,
																	"领取失败，请重试");
														}
													}
												});
											}
										}
									});

						}
					}
				});
			} else if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) == C.TASK_FINISH) {// 已完成
			}
			break;
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}
}
